<?php
/**
 * Created by PhpStorm.
 * User: wdt
 * Date: 2016/3/29
 * Time: 18:28
 */

namespace front\modules\web\controllers;


use backend\modules\v1\models\Product;
use front\controllers\WebBaseController;
use goods\services\ProductService;
use goods\services\ShopCategoryProductService;
use Overtrue\Wechat\Utils\Arr;
use yii\helpers\ArrayHelper;

class SearchController extends WebBaseController{

    public $layout = false;

    /**
     * 搜索页面
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 搜索结果商品列表
     * @return string
     */
    public function actionList()
    {
        $data = \Yii::$app->request->get();
        $keyWords = \Yii::$app->request->get('keyWords');
        //去除用户输入的空格
        $keyWords = str_replace(' ','',$keyWords);

        //如果传递了页面参数，即为分页ajax请求
        if (isset($data['page']) && isset($data['pre-page'])) {
            $data = ShopCategoryProductService::searchList(['name' => $keyWords,'type' => 1,'status' => 1]);
            $data = ArrayHelper::toArray($data);

            //根据商品ID获取商品显示
            foreach ($data as $k=>$v) {
                $product = ArrayHelper::toArray(ProductService::ProductInfo($v));
                if ($product['code'] == 1){
                    continue;
                }
                $product = $product['result']['productInfo'];
                $data[$k]['name'] = $product['name'];
                $img = \goods\models\Product::getThumbList($v['pid']);
                $data[$k]['img'] = $img.'@1e_1c_0o_0l_150h_150w_100q.jpg';
                $data[$k]['price'] = $product['price'];
            }

            echo trim($_GET['funcName']).'('.json_encode($data).')';
        } else {
            $data = ShopCategoryProductService::searchList(['name' => $keyWords,'type' => 1,'status' => 1]);
            $data = ArrayHelper::toArray($data);

            //根据商品ID获取商品表中商品信息
            foreach ($data as $k=>$v) {
                $product = ArrayHelper::toArray(ProductService::ProductInfo($v));
                if ($product['code'] == 1){
                    continue;
                }
                $product = $product['result']['productInfo'];
                $data[$k]['name'] = $product['name'];
                $img = \goods\models\Product::getThumbList($v['pid']);
                $data[$k]['img'] = $img.'@1e_1c_0o_0l_150h_150w_100q.jpg';
                $data[$k]['price'] = $product['price'];
            }

            return $this->render('list', [
                'value' => $keyWords,
                'data' => $data,
            ]);
        }
    }
}